''' @author:gxj 2018/11 '''
from django.shortcuts import render,redirect,HttpResponseRedirect,HttpResponse
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.views import View
import datetime,logging
from app02.sql import *
import logging
LOGGER=logging.getLogger()

# Create your views here.
'''
# cookies
def login(request):
    print('COOKIES',request.COOKIES)
    print('SESSION',request.session)
    if request.method =='POST':
        name = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if name =='bob' and pwd =='123':
            ret = redirect('/app02/home/')
            ret.set_cookie('userName',{'name':""},max_age=30*3600,expires=datetime.datetime.utcnow()+datetime.timedelta(minutes=30))
            # 设置cookies有限时间为10秒
            return ret
    return render(request,'login.html',locals())

def home(request):

    if request.COOKIES.get('userName',None):
        return render(request,'home.html',locals())
    else:
        return redirect('/app02/login/')
'''
'''        cookies+session              '''

class CBV(View):
    # 'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'
    def dispatch(self,request,*args,**kwargs):
        logging.log()
        result= super(CBV,self).dispatch(request,*args,**kwargs)

        return result

    def get(self):
        return render(request,'cbv.html')

    def post(self):
        ret=HttpResponse('cbv.POST')
        ret['h1']='v1'
        ret.set_cookie('c1','v2')
        # 添加相应头
        return ret

from django import forms
from django.forms import fields
from django.forms import widgets
import time,json

class Forms(forms.Form):
    user = fields.CharField(
        required = True,     #必填字段
        max_length=12,
        min_length=6,
        error_messages ={"required":"用户名不能为空！！","max_length":'最大长度为12',"min_length":'最小长度为6'},  #显示中文错误提示
        widget =widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})  #自动生成input框

    )
    passWord = fields.CharField(
        required=True,
        max_length=12,
        min_length=6,
        error_messages={"required":'密码不能为空！！',"max_length":'最大长度为12',"min_length":'最小长度为6'},
        widget=widgets.TextInput(attrs={'placeholder':"请输入密码","type":"passWord","class":"from-control"})
    )
    age = fields.IntegerField(
        required=True,
        error_messages={"required":'年龄不能为空！！'},
        widget=widgets.TextInput(attrs={'placeholder':"请输入年龄","class":"from-control"})
    )

class RegForms(forms.Form):

    userName = fields.CharField(
        required = True,     #必填字段
        max_length=12,
        min_length=6,
        error_messages ={"required":"用户名不能为空！！","max_length":'最大长度为12',"min_length":'最小长度为6'},  #显示中文错误提示
        widget =widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})  #自动生成input框

    )
    email =fields.EmailField(
        required=True,
        max_length=32,
        min_length=12,
        error_messages={"required":'联系邮箱不能为空！！',"max_length":'最大长度为32',"min_length":'最小长度为12'},
        widget=widgets.TextInput(attrs={'placeholder':"请输入联系邮箱","class":"from-control"})
    )
    passWord = fields.CharField(
        required=True,
        max_length=12,
        min_length=6,
        error_messages={"required":'密码不能为空！！',"max_length":'最大长度为12',"min_length":'最小长度为6'},
        widget=widgets.TextInput(attrs={'placeholder':"请输入密码","type":"passWord","class":"from-control"})
    )
    sex =fields.CharField(
        initial=1,# 默认选中1
        widget=widgets.RadioSelect(choices=((1,'男'),(2,'女')))
    )

    city =fields.CharField(
        initial=1,# 默认选中1F
        widget=widgets.Select(choices=((1,'北京'),(2,'重庆')))
    )

    hobby =fields.MultipleChoiceField(
        initial=[1,],
        choices=((1,'网游'),(2,'桌游'),(3,'篮球'),(4,'足球')),# 取数据库的值
        widget=widgets.CheckboxSelectMultiple
    )
    def __init__(self,*args,**kwargs):
        super(RegForms,self).__init__(*args,**kwargs)
        # self.fields['hobby'].widget.choices='select * from db_ems' 更新数据

def login(request):
    if request.method=='GET':
        obj = Forms()
        return render(request,'login.html',{"obj":obj})
    else:
        obj = Forms(request.POST)
        if obj.is_valid():# 开始验证
            print('COOKIES',request.COOKIES)
            print('SESSION',request.session)
            print(obj.cleaned_data)
            user = 'bob001'
            pwd = '123123'
            if obj.cleaned_data['user'] =='bob001' and obj.cleaned_data['passWord'] =='123123':

                request.session['is_login'] = True
                request.session['user_info'] = {'userName':user,'passWord':pwd}
                print(request.session['is_login'])
                print('user_info------',request.session['user_info'])
                return redirect('/app02/home/')
                # return render(request,'/app02/home/',)
        return render(request,'login.html',{'obj':obj})



def register(request):
    if request.method=='GET':
        obj = RegForms()
        return render(request,'register.html',{'obj':obj})
    else:
        obj = RegForms(request.POST)
        if obj.is_valid():
            '''数据写入倒库、并跳转至登录页面'''
            print(obj.cleaned_data)
            try:
                import time
                registerTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                sql='insert into db_ems.app02_client (userName,email,passWord,sex,city,hobby,registerTime) VALUES (%s,%s,%s,%s,%s,%s,%s)' %(
                        obj.cleaned_data.userName,obj.cleaned_data.email,obj.cleaned_data.passWord,obj.cleaned_data.sex,
                        obj.cleaned_data.city,obj.cleaned_data.hobby,registerTime)
                sqlwrite(spl)
                return redirect('/appo2/login')
            except Exception as e:
                LOGGER.error(e)
        '''保留原页面填写信息 给出错误提示'''
        return render(request,'register.html',{'obj':obj})


class zhuceForms(forms.Form):

    userName = fields.CharField(
        required = True,     #必填字段
        max_length=12,
        min_length=6,
        error_messages ={"required":"用户名不能为空！！","max_length":'最大长度为12',"min_length":'最小长度为6'},  #显示中文错误提示
        # widget =widgets.TextInput(attrs={"placeholder":"请输入用户名","class":"form-control"})  #自动生成input框

    )
    email =fields.EmailField(
        required=True,
        max_length=32,
        min_length=12,
        error_messages={"required":'联系邮箱不能为空！！',"max_length":'最大长度为32',"min_length":'最小长度为12'},
        # widget=widgets.TextInput(attrs={'placeholder':"请输入联系邮箱","class":"from-control"})
    )
    passWord = fields.CharField(
        required=True,
        max_length=12,
        min_length=6,
        error_messages={"required":'密码不能为空！！',"max_length":'最大长度为12',"min_length":'最小长度为6'},
        # widget=widgets.TextInput(attrs={'placeholder':"请输入密码","type":"passWord","class":"from-control"})
    )
    sex =fields.CharField(
        required=True,
        error_messages={"required":'性别不能为空！！'}
        # initial=1,# 默认选中1
        # widget=widgets.RadioSelect(choices=((1,'男'),(2,'女')))
    )

    city =fields.CharField(
        required=True,
        error_messages={"required":'城市不能为空！！'}
        # initial=1,# 默认选中1F
        # widget=widgets.Select(choices=((1,'北京'),(2,'重庆')))
    )

    hobby =fields.MultipleChoiceField(
        required=True,
        error_messages={"required":'爱好不能为空！！'}
        # initial=[1,],
        # choices=((1,'网游'),(2,'桌游'),(3,'篮球'),(4,'足球')),# 取数据库的值
        # widget=widgets.CheckboxSelectMultiple
    )
    # 自定义验证单字段方法 clean_加字段名 必须有返回值 出错抛出ValidationError
    def clean_username(self):
        '''判断用户是否存在'''
        v=self.cleaned_data['username']
        sql='select COUNT (username) from user '
        sqlread(sql)
        if sqlread(sql)>0:
            '''数据库已存在'''
            raise ValidationError('用户名已存在')

        return self.cleaned_data['username']

    # 自定义验证单字段方法 clean必须有返回值 出错抛出ValidationError

    def clean_email(self):
        return self.cleaned_data['email']


    def clean(self):
        '''联合唯一判断 多字段组合唯一'''
        value_dict = self.cleaned_data
        v =value_dict.get('username')
        v2=value_dict.get('userId')
        if v1=='root' and v2==1:
            raise ValidationError('联合字段不唯一')
        return self.cleaned_data

    def __init__(self,*args,**kwargs): #重写init方法，时时更新
        super(zhuceForms,self).__init__(*args,**kwargs)
        # self.fields['hobby'].widget.choices='select * from db_ems' 更新数据
def zhuce(request):
    if request.method=='GET':
        # obj = zhuceForms()
        data={'河北省':['石家庄','秦皇岛','保定','廊坊','唐山'],
               '陕西省':['西安','咸阳','宝鸡','延安','安康','万源'],
               '甘肃省':['兰州','天水','武威','玉门','嘉峪关','平凉','陇南','定西','张掖','酒泉','白银']
               }
        print(type(data))
        return HttpResponse(json.dumps(data),content_type='application/json')
    else:
        ret ={'status':None,'message':None}
        obj = zhuceForms(request.POST)
        # print(obj)
        if obj.is_valid():
            '''数据写入倒库、并跳转至登录页面'''
            print(obj.cleaned_data)
            try:
                registerTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                sql='insert into db_ems.app02_client (userName,email,passWord,sex,city,hobby,registerTime) VALUES (%s,%s,%s,%s,%s,%s,%s)' %(
                    obj.cleaned_data.userName,obj.cleaned_data.email,obj.cleaned_data.passWord,obj.cleaned_data.sex,
                    obj.cleaned_data.city,obj.cleaned_data.hobby,registerTime)
                sqlwrite(spl)
                # return redirect('/appo2/login')
                ret['status']=200
                return HttpResponse(json.dumps(ret),content_type='application/json')
            except Exception as e:
                LOGGER.error(e)
        '''保留原页面填写信息 给出错误提示'''
        ret['message']= obj.errors
        print(ret)
        print(type(obj.errors))
        '''
        obj.errors.message ={
            __all__:()
            username:
        }
        '''
        print('error--->',obj.errors)
        return HttpResponse(json.dumps(ret),content_type='application/json')








import logging
LOGGER=logging.getLogger()

def autho_fun(func):
    def wrapper(request, *args, **kwargs):
        # if request.session.get['is_login',None] :
        if request.session['is_login']:
            res = func(request, *args, **kwargs)
            return res
        else:
            return redirect("/app02/login/")
    return wrapper

@autho_fun
def home(request):
    # if request.session.get('is_login',False):
    #     user = request.session.get('user',None)
    #     return render(request,'home.html',locals())
    # else:
    #     return redirect('/app02/login/')
        return render(request,'home.html',locals())

def logout(request):
    try:
        del request.session['is_login']
    except KeyError:
        pass
    return HttpResponse(" logged out success ")


def teacher(request):
    sql='select * from  db_ems.student'
    teacherList= sqlread(sql)
    return render(request,'teacher.html',locals())

def sourse(request):
    return HttpResponse(" ok ")

def classes(request):
    return HttpResponse(" ok ")